package com.dao.impl;

import com.dao.IClassesDAO;
import com.db.ConnectionManager;
import com.vo.Classes;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class ClassesDAOImpl implements IClassesDAO {
    @Override
    public Classes findClassesById(Integer classId) throws Exception {
        Connection con = ConnectionManager.getConnection();
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        Classes classes = null;
        try {
            con = ConnectionManager.getConnection();
            String sql = "select * from classes where classId = ?";
            pstmt = con.prepareStatement(sql);
            pstmt.setInt(1, classId);
            rs = pstmt.executeQuery();
            if (rs.next()) {
                classes = new Classes();
                classes.setClassId(classId);
                classes.setClassName(rs.getString("class_name"));
            }
        }catch (SQLException e) {
            e.printStackTrace();
        }finally {
            ConnectionManager.closeStatement(pstmt);
            ConnectionManager.closeConnection(con);
        }
        return classes;
    }

    @Override
    public List<Classes> findAllClasses() throws Exception {
        Connection con = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        List<Classes> all = new ArrayList<Classes>();
        try{
            con = ConnectionManager.getConnection();
            pstmt = con.prepareStatement("select * from classes");
            rs = pstmt.executeQuery();
            Classes classes = null;
            while(rs.next()){
                classes = new Classes();
                classes.setClassId(rs.getInt("classId"));
                classes.setClassName(rs.getString("className"));
                all.add(classes);
            }
        }catch (SQLException e){
            e.printStackTrace();
        }finally {
            ConnectionManager.closeStatement(pstmt);
            ConnectionManager.closeConnection(con);
        }
        return all;
    }
}
